<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>正则输入框验证</title>
  </head>
  <body>
    <input
      type="text"
      placeholder="输入不少于5位的用户名，并且只能为字母开始后跟数字或者下划线；"
      style="width: 100%"
    />
    <div id="error"></div>
    <script>
      let input = document.querySelector('input')
      let error = document.querySelector('#error')
      input.addEventListener('input', function () {
        error.innerHTML = ''
        let reg = /^[a-zA-Z]+\w*/
        console.log(this.value.match(reg))
        if (this.value.match(reg) == null) {
          error.innerHTML = '请输入以字母开始后跟数字或者下划线；'
        } else if (this.value.length < 5) {
          error.innerHTML = '请输入不少于5位的用户名'
        }
      })
    </script>
  </body>
</html>
